<template>
  <a-collapse :key="globalKey">
    <a-collapse-panel key="1" :showArrow="false" header="+ 样式信息">
      <table class="mars-primary-table" border="1" bordercolor="#ffffff" cellspacing="0" cellpadding="0">
        <template v-for="(item, i) in compConfig" :key="i">
          <tr>
            <td>{{ item.label }}</td>
            <td>
              <base-comp
                :type="item.type"
                size="small"
                v-model:value="optionsValue[item.name]"
                :min="item.min || item.min === 0 ? item.min : -Infinity"
                :max="item.max || item.max === 0 ? item.max : Infinity"
                :step="item.step || 0.1"
                :options="item.data || []"
                @change="updateValue(item, item.data)"
                :tofixed="item.toFixed"
              ></base-comp>
            </td>
          </tr>
        </template>
      </table>
    </a-collapse-panel>
  </a-collapse>
</template>

<script setup>
import BaseComp from "@/widgets/overlay-editor/component/base-comp.vue"
import { ref, toRaw, watch } from "vue"
import _ from "lodash"

const emit = defineEmits(["valueChange"])

const optionsValue = ref({})

const props = defineProps({
  options: Object,
  compConfig: Object
})

const globalKey = ref(0)

watch(
  props,
  () => {
    if (props && props.options) {
      globalKey.value++
      setDefault() // 处理初始化默认值（不做任何修改之前的状态）
    }
  },
  {
    immediate: true
  }
)

// 设置初始化的默认值
function setDefault () {
  optionsValue.value = _.cloneDeep(props.options)

  props.compConfig.forEach((item) => {
    optionsValue.value[item.name] = optionsValue.value[item.name] ?? getViewDefval(item, optionsValue.value) // 数据中没有的地方使用默认值
  })
}

function getViewDefval (config, styleOptions) {
  if (typeof config.defval === "function") {
    return config.defval(styleOptions, optionsValue.value)
  } else {
    return config.defval
  }
}


function updateValue (item) {
  const val = optionsValue.value[item.name]
  const data = {
    [item.name]: val
  }

  emit("valueChange", data)
}

</script>

<style scoped lang="less">

</style>
